package com.xyd.servlet;

import com.xyd.util.CookieUtil;
import com.xyd.util.JsonUtil;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 类描述：购物车删除功能
 *
 * @author 张吉哲
 * @date 2021/1/13 13:45
 */
@WebServlet("/cartDeleteServlet")
public class CartDeleteServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String eodIdStr = request.getParameter("eodId");
    String[] epIds = eodIdStr.split(",");
    Cookie[] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
      if (CookieUtil.getCookieName().equals(cookie.getName())) {
        String value = cookie.getValue();
        StringBuilder newValue = new StringBuilder();
        String[] split = value.split("\\*");
        for (String s : split) {
          String[] split1 = s.split(",");
          boolean boo = true;
          for (String epId : epIds) {
            if (split1[0].equals(epId)) {
              boo = false;
              break;
            }
          }
          if (boo) {
            newValue.append(split1[0]).append(",").append(split1[1]).append("*");
          }
        }
        CookieUtil.fixCookie(cookie, newValue.toString(), response);
        break;
      }
    }
    JsonUtil.toJson(response, true);
  }

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doPost(request, response);
  }
}
